package org.example.course.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.course.common.Constast;
import org.example.course.common.DataGridView;
import org.example.course.common.utils.WebUtils;
import org.example.course.domain.User;
import org.example.course.dto.UserModel;
import org.example.course.mapper.UserMapper;
import org.example.course.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Classname UserServiceImpl
 * @Description 用户
 * @Date 2020/5/8 13:07
 * @Created by
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper mapper;


    @Override
    public User loginByNameAndPwd(String loginName, String password) {

        User user = mapper.findByLoginNameAndPassword(loginName, password);

        return user;
    }

    @Override
    public DataGridView findPage(UserModel userModel) {
        //分页插件 PageHelper
        PageHelper.startPage(userModel.getPage(), userModel.getLimit());
        List<User> list = mapper.findAll(userModel);
        //PageHelper 获取分页信息
        PageInfo<User> pageInfo = new PageInfo(list);

        return new DataGridView(pageInfo.getTotal(), list);
    }

    @Override
    public boolean create(User user) {
        user.setPassword(Constast.USER_DEFAULT_PASSWORD);
        //返回影响行数
        int msg = mapper.insert(user);
        return msg > 0;
    }

    @Override
    public boolean update(User user) {
        int msg = mapper.updateByPrimaryKeySelective(user);
        return msg > 0;
    }

    @Override
    public boolean resetPassword(String id) {
        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setPassword(Constast.USER_DEFAULT_PASSWORD);
        int msg = mapper.updateByPrimaryKeySelective(user);
        return msg > 0;
    }

    @Override
    public boolean delete(String id) {
        int msg = mapper.deleteByPrimaryKey(Integer.valueOf(id));
        return msg > 0;
    }

    @Override
    public boolean updateUserPwd(String oldPassword, String password) {

        Integer id = WebUtils.getSessionUser().getId();
        User user = new User();
        user.setId(id);
        User dbUser = mapper.findByIdAndPassword(id, oldPassword);
        if (null == dbUser) {
            return false;
        }
        user.setPassword(password);
        int msg = mapper.updateByPrimaryKeySelective(user);
        return msg > 0;
    }
}
